#include<iostream>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<string.h>

using namespace std;

//shmget,shmat,shmdt,shmctl函数演示system V共享内存操作的示例代码
//创建-挂接，使用，分离，销毁
#define SHM_SIZE 1024
#define KEY 55611
int main()
{
    int shmid;
    key_t key=KEY;
    char *shmaddr;
    shmid=shmget(key,sizeof(key),IPC_CREAT|IPC_EXCL|0666);
    if(shmid==-1)
    {
        perror("shmget");
        return 1;
    }
    printf("Shared memory segment created,shmid:%d\n",shmid);
    //挂接
    shmaddr=(char*)shmat(shmid,NULL,0);
    if(shmaddr==(void*)-1)
    {
        perror("shmat");
        return 1;
    }
    printf("Shared memory attached at address:%p\n",shmaddr);
    //使用共享内存，写入或者读取
    const char*msg="Hello,Shared Memory!";
    for(int i=0;msg[i]!='\0';i++)
    {
        shmaddr[i]=msg[i];
    }
    shmaddr[strlen(msg)]='\0';
    printf("Content in shared memory:%s\n",shmaddr);
    //分离
    if(shmdt(shmaddr)==-1)
    {
        perror("shmdt");
        return 1;
    }
    printf("Shared memory detached\n");
    //销毁
    if(shmctl(shmid,IPC_RMID,NULL)==-1)
    {
        perror("shmctl");
        return 1;
    }
    printf("Shared memory segment marked for destrruction\n");
    return 0;
}